package com.example.simpleforum.servlet;

import com.example.simpleforum.dao.UserDao;
import com.example.simpleforum.model.User;
import com.example.simpleforum.util.PasswordUtil;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;

/**
 * 用户注册Servlet
 */
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // GET请求直接转发到注册页面
        request.getRequestDispatcher("/register.jsp").forward(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取表单数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");
        
        // 表单验证
        if (username == null || username.trim().isEmpty()) {
            request.setAttribute("error", "用户名不能为空");
            request.getRequestDispatcher("/register.jsp").forward(request, response);
            return;
        }
        
        if (password == null || password.trim().isEmpty()) {
            request.setAttribute("error", "密码不能为空");
            request.getRequestDispatcher("/register.jsp").forward(request, response);
            return;
        }
        
        if (!password.equals(confirmPassword)) {
            request.setAttribute("error", "两次输入的密码不一致");
            request.getRequestDispatcher("/register.jsp").forward(request, response);
            return;
        }
        
        // 检查用户名是否已存在
        UserDao userDao = new UserDao();
        if (userDao.isUsernameExists(username)) {
            request.setAttribute("error", "用户名已存在");
            request.getRequestDispatcher("/register.jsp").forward(request, response);
            return;
        }
        
        // 创建用户对象
        User user = new User();
        user.setUsername(username);
        // 密码加密
        user.setPassword(PasswordUtil.encrypt(password));
        user.setRegisterTime(new Timestamp(System.currentTimeMillis()));
        
        // 保存用户
        int userId = userDao.addUser(user);
        if (userId > 0) {
            // 注册成功，重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/login.jsp?success=true");
        } else {
            // 注册失败
            request.setAttribute("error", "注册失败，请稍后再试");
            request.getRequestDispatcher("/register.jsp").forward(request, response);
        }
    }
}